new Vue({
  el: "#app",
  mixins: [Query], //组件配置文件，路径/utils/components.js
  data() {
    return {
      form: {
        //查询筛选
        value: "",
        value2: "-",
        PageNumber: 1, //页码
        RowAmount: 20,
        Condition: utf8ToBase64("%%,%%"),
        ExtensionCondition: utf8ToBase64(
          getCookie("enterprise") != "1"
            ? `AND enterprise_info.Enterprise_Info_SerialNumber='${getCookie(
                "enterprise"
              )}'`
            : ""
        ),
      },
    };
  },
  mounted() {
    /**
     * 组件配置文件中自动执行方法
     * 1.this.getColumn(); //查询表头数据
     * 2.this.getList(this.form); //查询表格数据
     * 3.this.getTreeData();//查询树
     */
  },
  methods: {
    handleLook(row) {
      try {
        const { primaryKey } = $("#table").data("options");
        window.location.href =
          "./add.html?action=Modify&type=1&nodeKey=" + row[primaryKey];
      } catch (error) {
        console.error(error);
        this.$message({
          message: "系统错误，请联系开发者!",
          type: "error",
        });
      }
    },

    handleSerach() {
      //筛选
      this.form.Condition = utf8ToBase64(
        `%${this.form.value}%,%${
          this.form.value2 == "-" ? "" : this.form.value2
        }%`
      );
      this.form.PageNumber = 1; //重置页码
      this.getList(this.form);
    },

    handleBack() {
      window.history.back();
    },
    handleAdd() {
        window.location.href = "../../../register.html"; 
    },
    async getColumn(is = true) {
      //获取表头、权限数据
      try {
        const [data, role] = await Promise.all([
          generalApi.generalQueryBySQLSerialNumber({
            SQLSerialNumber: "s_base_sql_table_config",
            Condition: utf8ToBase64(
              `${getCookie(
                "user"
              )},%${"view/detection/enterprise/index.html"}%,${getCookie(
                "user"
              )},%${"view/detection/enterprise/index.html"}%`
            ),
            ExtensionCondition: "",
          }),
          generalApi.generalQueryBySQLSerialNumber({
            SQLSerialNumber: "s_base_button_config",
            Condition: utf8ToBase64(
              `${getCookie("user")},${"view/detection/enterprise/index.html"}`
            ),
            ExtensionCondition: "",
          }),
        ]);
        this.buttonRole = Object.entries(role[0] || {}).reduce(
          (acc, [key, value]) => {
            acc[key] = value === "1"; // 1 → true, 0 → false
            return acc;
          },
          {}
        );
        if (data.length > 0) {
          this.columns = data;
          if (is) {
            //默认正常初始化查询
            this.getList(this.form);
          } else {
            //调整显示字段
            this.isUpdate = false;
            this.$nextTick(() => {
              this.isUpdate = true;
            });
          }
        } else {
          this.$message({
            message: "未配置数据源，请联系开发者!",
            type: "error",
          });
        }
      } catch (error) {
        console.error(error);
        this.$message({
          message: "系统错误，请联系开发者!",
          type: "error",
        });
      }
    },
    async getList(data) {
      //获取表格数据
      this.loading = true;
      try {
        const res = await generalApi.generalPaginationQueryBySQLSerialNumber({
          Model_Url: "view/detection/enterprise/index.html",
          PaginationNumber: data.PageNumber,
          RowAmount: data.RowAmount,
          Condition: data.Condition,
          ExtensionCondition: data.ExtensionCondition || "",
        });
        this.loading = false;
        this.Total = res.TotalRows; //总数量
        this.tableData = res.Rows;
        this.isUpdate = false;
        this.$nextTick(() => {
          this.isUpdate = true;
        });
      } catch (error) {
        this.loading = false;
        this.$message({
          message: "系统错误，请联系开发者!",
          type: "error",
        });
      }
    },
    handleAudit(row) {
      //审核
      this.$confirm(
        `此操作将${
          row.Row_Status == "2" ? "审核" : "取消审核"
        }该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          try {
            const { tableName, primaryKey } = $("#table").data("options");
            httpRequest({
              url: "/generalBusiness/generalQueryByTableNameWithOriginal",
              data: {
                Data: tableName,
                Condition: `${primaryKey}='${row[primaryKey]}'`,
              },
            })
              .then((data) => {
                if (data.length == 1) {
                  data[0].Row_Status = row.Row_Status == "2" ? "0" : "2";
                  let lJSONObject_Modify = new Object();
                  lJSONObject_Modify[tableName] = data;
                  //组合
                  let lJSONObject_DataSet = {
                    Modify: lJSONObject_Modify,
                    Add: {},
                  };
                  let Operation_Main = JSON.stringify(
                    deepClone(lJSONObject_DataSet)
                  );
                  lJSONObject_DataSet["Add"]["base_operation_log"] = [
                    {
                      Operation_Type: "2",
                      Operation_Path: "view/detection/enterprise/index.html",
                      Operation_Description:
                        (row.Row_Status == "0" ? "审核" : "取消审核") +
                        "商户数据",
                      Operation_Main,
                      Operation_Interface: "generalSaveByRequestBody",
                      Operation_IP: getIpAddress(),
                    },
                  ];
                  httpRequest({
                    contentType: "JSON",
                    url: "/generalBusiness/generalSaveByRequestBody",
                    data: JSON.stringify({
                      Data: lJSONObject_DataSet,
                    }),
                  })
                    .then((res) => {
                      if (res.Status == "success") {
                        this.getList(this.form);
                        this.$message.success(
                          (row.Row_Status == "2" ? "审核" : "取消审核") + "成功"
                        );
                      } else {
                        this.$message.error(
                          (row.Row_Status == "2" ? "审核" : "取消审核") +
                            "失败，请重试！"
                        );
                      }
                    })
                    .catch((xhr) => {
                      this.$message({
                        message: "系统错误，请联系开发者!",
                        type: "error",
                      });
                    });
                }
              })
              .catch((xhr) => {
                this.$message({
                  message: "系统错误，请联系开发者!",
                  type: "error",
                });
              });
          } catch (error) {
            console.error(error);
            this.$message({
              message: "系统错误，请联系开发者!",
              type: "error",
            });
          }
        })
        .catch(() => {});
    },

    handleRefuse(row) {
      //拒绝
      this.$prompt(
        `此操作将${
          row.Row_Status == "2" ? "拒绝" : "取消拒绝"
        }该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/,
          type: "warning",
        }
      )
        .then(({ value }) => {
          try {
            const { tableName, primaryKey } = $("#table").data("options");
            httpRequest({
              url: "/generalBusiness/generalQueryByTableNameWithOriginal",
              data: {
                Data: tableName,
                Condition: `${primaryKey}='${row[primaryKey]}'`,
              },
            })
              .then((data) => {
                if (data.length == 1) {
                  data[0].Row_Status = row.Row_Status == "2" ? "3" : "2";
                  let lJSONObject_Modify = new Object();
                  lJSONObject_Modify[tableName] = data;
                  //组合

                  let lJSONObject_DataSet = {
                    Modify: lJSONObject_Modify,
                    Add: {
                      enterprise_examine_log: [
                        {
                          Enterprise_Info_SerialNumber: row[primaryKey],
                          Reason: value,
                        },
                      ],
                    },
                  };
                  let Operation_Main = JSON.stringify(
                    deepClone(lJSONObject_DataSet)
                  );
                  lJSONObject_DataSet["Add"]["base_operation_log"] = [
                    {
                      Operation_Type: "3",
                      Operation_Path: "view/detection/enterprise/index.html",
                      Operation_Description:
                        (row.Row_Status == "3" ? "拒绝" : "取消拒绝") +
                        "商户数据",
                      Operation_Main,
                      Operation_Interface: "generalSaveByRequestBody",
                      Operation_IP: getIpAddress(),
                    },
                  ];

                  httpRequest({
                    contentType: "JSON",
                    url: "/generalBusiness/generalSaveByRequestBody",
                    data: JSON.stringify({
                      Data: lJSONObject_DataSet,
                    }),
                  })
                    .then((res) => {
                      if (res.Status == "success") {
                        this.getList(this.form);
                        this.$message.success(
                          (row.Row_Status == "2" ? "拒绝" : "取消拒绝") + "成功"
                        );
                      } else {
                        this.$message.error(
                          (row.Row_Status == "2" ? "拒绝" : "取消拒绝") +
                            "失败，请重试！"
                        );
                      }
                    })
                    .catch((xhr) => {
                      this.$message({
                        message: "系统错误，请联系开发者1!",
                        type: "error",
                      });
                    });
                }
              })
              .catch((xhr) => {
                this.$message({
                  message: "系统错误，请联系开发者2!",
                  type: "error",
                });
              });
          } catch (error) {
            console.error(error);
            this.$message({
              message: "系统错误，请联系开发者3!",
              type: "error",
            });
          }
        })
        .catch(() => {});
    },
  },
});
